import axios from 'axios'
import Vue from 'vue'

axios.defaults.timeout = 30 * 1000;

const createConfig = {
  withCredentials: true, // 是否允许携带cookie
  timeout: 1000 * 10 // 请求最大超时时间（超时后直接返回请求超时，不再等待请求）
}

// createConfig.baseURL = 'http://127.0.0.1:9900'

// 环境变量
const _axios = axios.create(createConfig)

//请求拦截  添加token
_axios.interceptors.request.use((config) => {
  config.headers.Authorization = Vue.ls.get('token');
  config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  return config
}, (error) => {
  return Promise.reject(error);
})

//返回拦截,错误码
_axios.interceptors.response.use(function(response) {
  if (response.data.code == 200) {
    return Promise.resolve(response.data);
  } else {
    window.vm.$message.error(response.data.message)
    return Promise.reject(response.data);
  }
}, function(err) {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        window.vm.$message.error('错误请求了啊....')
        break;
      case 401:
        window.vm.$message.error('token过期啦,去重新登录吧~~！')
        setTimeout(() => {
          localStorage.clear();
          sessionStorage.clear();
          // location.reload();
        }, 2000);
        break;
      case 403:
        window.vm.$message.error('拒绝访问!!!')
        break;
      case 404:
        window.vm.$message.error('请求歪了~~ 快找找哪里的锅~~!')
        break;
      case 405:
        window.vm.$message.error('请求方法未允许...desu...')
        break;
      case 408:
        window.vm.$message.error('请求超.超..超时le...')
        break;
      case 500:
        window.vm.$message.error('丢锅 ♪(^∇^*) ~~  是服务器端出错呢~~！')
        break;
      case 501:
        window.vm.$message.error('网络未实现 (((φ(◎ロ◎;)φ)))...')
        break;
      case 502:
        window.vm.$message.error('网络错误 (￢︿̫̿￢☆)！！！')
        break;
      case 503:
        window.vm.$message.error('服务不可用 略略略 ~~~！')
        break;
      case 504:
        window.vm.$message.error('网....络......超...时.......')
        break;
      case 505:
        window.vm.$message.error('http版本不支持该请求...大概？')
        break;
      default:
        window.vm.$message.error(`连接错误${err.response.status}`)
    }
  } else {
    window.vm.$message.error('sorry~~ 连接服务器失败了哈...')
  }
  return Promise.reject(err.response)
});

export const GET = (url, params) => {
  return _axios.get(`${url}`, {params: params}).then(res => res.data)
}
export const POST = (url, params) => {
  return _axios.post(`${url}`, params).then(res => res.data)
}
export const PUT = (url, params) => {
  return _axios.put(`${url}`, params).then(res => res.data)
}
export const DELETE = (url, params) => {
  return _axios.delete(`${url}`, {
    data: params
  }).then(res => res.data)
}
